package com.jyhs.maven.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
    public static String drive;
    public static String url;
    public static String username;
    public static String password;
    public Connection conn;
    public PreparedStatement ps;

    static {
        init();
    }

    public static void init() {
        Properties p = new Properties();
        InputStream in = BaseDao.class.getClassLoader().getResourceAsStream("t03spring.properties");
        try {
            p.load(in);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        drive = p.getProperty("driver");
        url = p.getProperty("url");
        username = p.getProperty("username");
        password = p.getProperty("password");
    }

    public ResultSet getSelect(String sql, Object... param) throws SQLException, ClassNotFoundException {
        getConnection();
        ResultSet rs=null;
        try {
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < param.length; i++) {
                ps.setObject(i + 1, param[i]);
            }
            rs = ps.executeQuery();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
//            close(conn,ps,null);
        }
        return rs;
    }

    public int getUpdate(String sql, Object... param) throws SQLException, ClassNotFoundException {
        getConnection();
        int count;
        try {
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < param.length; i++) {
                ps.setObject(i + 1, param[i]);
            }
            count = ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            close(conn,ps,null);
        }
        return count;
    }

    public void getConnection() throws ClassNotFoundException, SQLException {
        Class.forName(drive);
        conn = DriverManager.getConnection(url, username, password);
    }

    public void close(Connection conn, PreparedStatement ps, ResultSet rs) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

